<template>
    <div>
        <!-- <el-button type="primary" size="mini" style="float:right;margin:4px 0" @click="layoutDialog = true">页面布局</el-button> -->

        <vxe-table
            :header-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
            :footer-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
            :data="tableData"
            :key="tableKey + 'tableKey'"
            v-loading="loading"
            border
            stripe
            resizable
            :auto-resize="true"
            :sort-config="{
                defaultSort: { field: sortProp, order: sortOrder, orders: ['desc', 'asc', null] },
                remote: true,
            }"
            highlight-current-row
            @sort-change="changeTableSort"
            :resizable-config="{ minWidth: '60' }"
            ref="table"
            show-header-overflow="tooltip"
            show-footer-overflow="tooltip"
            header-align="center"
        >
            <vxe-column
                v-for="item in showFieldList"
                :field="item.id"
                :title="item.content"
                :key="item.content"
                :align="getAlign(item)"
                :min-width="item.minWidth || '105px'"
                show-overflow="tooltip"
                sortable
            >
                <template slot-scope="scope">
                    <span v-if="['firstSettleDate', 'secondSettleDate'].includes(item.id)">
                        {{ dateFormat(scope.row[item.id]) || '--' }}
                    </span>
                    <span v-else-if="item.id == 'date'">
                        {{ dateFormat(scope.row[item.id]) || '--' }} {{ timeFormat(scope.row['time']) }}
                    </span>
                    <span v-else-if="['dealAmount', 'dealBalance', 'fee', 'rate'].includes(item.id)">
                        {{ numberFormat(scope.row[item.id], 2) || '--' }}
                    </span>
                    <span v-else-if="['hgDays', 'useDays'].includes(item.id)">
                        {{ scope.row[item.id] + '' == '0' ? 0 : numberFormat(scope.row[item.id]) || '--' }}
                    </span>
                    <span v-else>
                        {{ scope.row[item.id] === 0 || (scope.row[item.id] && (scope.row[item.id] + '').trim()) ? scope.row[item.id] : '--' }}
                    </span>
                </template>
            </vxe-column>
        </vxe-table>
        <risk-pagination :paging="page" @page-change="pageRet"></risk-pagination>

        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            :reset-no-selected-field-list="resetNoSelectedFieldList"
            table-name="TN_HG_TRANSACTION"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import RiskPagination from '@/common/components/risk-pagination.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import { dateFormat, numberFormat, timeFormat } from '@/utils/tools';
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({ name: 'BankHgTransaction', components: { RiskTableLayout, RiskPagination } })
export default class BankHgTransaction extends Vue {
    @Prop()
    transData: any;

    resetNoSelectedFieldList = [
        { id: 'fundId', content: ' 产品序号' },
        { id: 'fundCode', content: '产品编码' },
        { id: 'fundName', content: '产品名称' },
    ];
    numberFormat = numberFormat;
    dateFormat = dateFormat;
    timeFormat = timeFormat;
    layoutDialog: boolean = false; // 布局显示值

    showFieldList: any[] = []; // 展示字段

    selectedFieldList: any[] = []; // 已选字段

    fixedFieldList: any[] = [
        { id: 'serialNo', content: '成交序号(恒生)', minWidth: '140px', align: 'left' },
        { id: 'dealNo', content: '成交编号(恒生)', minWidth: '140px', align: 'left' },
    ];

    tableData: any[] = []; // 表格数据

    tableKey: number = -1;

    loading: boolean = false; // 页面渲染

    private sortProp: string = 'serialNo'; // 排序字段

    private sortOrder: string = 'asc'; // 排序方式

    sort: string = 'L_SERIAL_NO ASC'; // 默认排序字段

    private page: pages = {
        currentPage: 1,
        pageSize: 10,
        total: 0,
    };

    tableColumns = [
        { id: 'serialNo', content: '成交序号(恒生)', minWidth: '140px', align: 'left' },
        { id: 'dealNo', content: '成交编号(恒生)', minWidth: '140px', align: 'left' },
        { id: 'entrustSerialNo', content: '委托序号(恒生)', minWidth: '140px', align: 'left' },
        { id: 'batchSerialNo', content: '委托批号(恒生)', minWidth: '140px', align: 'left' },
        { id: 'dailyInstructionNo', content: '指令序号(恒生)', minWidth: '140px', align: 'left' },
        { id: 'instBatchSerialNo', content: '指令批号(恒生)', minWidth: '140px', align: 'left' },
        { id: 'fundId', content: ' 产品序号', align: 'left' },
        { id: 'fundCode', content: '产品编码', align: 'left' },
        { id: 'fundName', content: '产品名称', align: 'left' },
        { id: 'basecombiId', content: '组合编码', align: 'left' },
        { id: 'combiName', content: '组合名称', align: 'left' },
        { id: 'stockCode', content: '证券代码', align: 'left' },
        { id: 'stockNameSt', content: '证券名称', align: 'left' },
        { id: 'date', content: '成交日期', align: 'center', minWidth: '180px' },
        // { id: 'time', content: '成交时间', align: 'center' }, // businessTime
        { id: 'entrustDirection', content: '委托方向', align: 'center' },
        { id: 'investType', content: '投资类型', align: 'center' },
        { id: 'dealAmount', content: '成交数量' },
        { id: 'dealBalance', content: '成交金额' },
        { id: 'fee', content: '费用' },
        { id: 'settleSpeed', content: '清算速度' },
        { id: 'rate', content: '回购利率(%)', minWidth: '140px' },
        { id: 'hgDays', content: '回购天数' },
        { id: 'useDays', content: '实际占款天数', minWidth: '140px' },
        { id: 'firstSettleDate', content: '首次交割日', minWidth: '130px', align: 'center' },
        { id: 'secondSettleDate', content: '到期交割日', minWidth: '130px', align: 'center' },
        { id: 'firstSettleType', content: '首次交割方式', minWidth: '140px', align: 'center' },
        { id: 'secondSettleType', content: '到期交割方式', minWidth: '140px', align: 'center' },
        { id: 'rivalId', content: '交易对手编码', minWidth: '150px', align: 'left' },
        { id: 'tradeName', content: '交易对手名称', minWidth: '150px', align: 'left' },
        { id: 'cancelFlag', content: '撤单标志', align: 'center' },
        { id: 'operatorNo', content: '操作员编码', minWidth: '130px' },
        { id: 'operatorName', content: '操作员名称', minWidth: '130px', align: 'left' },

        // { id: 'businClass', content: '业务分类' },
        // { id: 'stockholderId', content: '股东代码' },
        // { id: 'marketName', content: '交易市场' },
        // { id: 'marketDate', content: '市场成交日期', minWidth: '150px' },
        // { id: 'dealPrice', content: '成交价格' },
        // { id: 'contractNo', content: '合同编号' },
        // { id: 'valid', content: '有效状态' },
        // { id: 'realdealCancelNo', content: '成交交撤销序号', minWidth: '160px' },
        // { id: 'cancelTime', content: '撤销时间' },
    ];

    // 排序字段
    sortableObj = {
        serialNo: 'L_SERIAL_NO',
        dealNo: 'VC_DEAL_NO',
        entrustSerialNo: 'L_ENTRUST_SERIAL_NO',
        batchSerialNo: 'L_BATCH_SERIAL_NO',
        dailyInstructionNo: 'L_DAILY_INSTRUCTION_NO',
        instBatchSerialNo: 'L_INST_BATCH_SERIAL_NO',
        fundId: 'L_FUND_ID',
        fundCode: 'VC_FUND_CODE',
        fundName: 'VC_FUND_NAME',
        basecombiId: 'L_BASECOMBI_ID',
        combiName: 'VC_COMBI_NAME',
        stockCode: 'VC_INTER_CODE',
        stockNameSt: 'VC_STOCK_NAME',
        date: 'CONCAT(L_DATE,L_TIME)',
        time: 'L_TIME',
        businessTime: 'L_BUSINESS_TIME',
        entrustDirection: 'C_ENTRUST_DIRECTION',
        dealAmount: 'L_DEAL_AMOUNT',
        dealBalance: 'EN_DEAL_BALANCE',
        operatorNo: 'L_OPERATOR_NO',
        operatorName: 'VC_OPERATOR_NAME',
        rivalId: 'VC_RIVALTRADER_ID', // rivaltraderId
        tradeName: 'VC_TRADER_NAME', // traderName

        investType: 'C_INVEST_TYPE_CODE',
        fee: 'EN_FEE',
        settleSpeed: 'L_SETTLE_SPEED_CODE',
        cancelFlag: 'C_CANCEL_FLAG',

        useDays: 'L_USE_DAYS',
        hgDays: 'L_HG_DAYS',
        rate: 'EN_RATE',
        secondSettleType: 'C_SECOND_SETTLE_TYPE',
        secondSettleDate: 'L_SECOND_SETTLE_DATE',
        firstSettleType: 'C_FIRST_SETTLE_TYPE',
        firstSettleDate: 'L_FIRST_SETTLE_DATE',

        // dealPrice: 'EN_DEAL_PRICE',
        // marketName: 'VC_MARKET_NAME',
        // businClass: 'C_BUSIN_CLASS',
        // stockholderId: 'VC_STOCKHOLDER_ID',
        // marketDate: 'L_MARKET_DATE',
        // time: 'L_TIME', //
        // contractNo: 'VC_CONTRACT_NO',
        // valid: 'C_VALID_CODE',
        // realdealCancelNo: 'L_REALDEAL_CANCEL_NO',
        // cancelTime: 'C_CANCEL_TIME',
    };

    isFirst: boolean = true; // 是否第一次

    currentRecord: any = {};
    @Watch('transData', { immediate: true, deep: true })
    async handleTab(nowVal, oldVal) {
        if (nowVal['activeTab'] == 'BankHgTransaction') {
            this.layoutDialog = nowVal.detailLayoutDialog;
            if (this.isFirst) {
                await this.queryLayout();
                this.getBankHgTransactionTableData();
                this.isFirst = false;
            } else if (
                !oldVal ||
                JSON.stringify(oldVal.clickRow) !== JSON.stringify(nowVal.clickRow) ||
                JSON.stringify(nowVal.clickRow) !== JSON.stringify(this.currentRecord)
            ) {
                this.getBankHgTransactionTableData();
            }
            this.currentRecord = JSON.parse(JSON.stringify(nowVal.clickRow));
        }
    }

    @Watch('layoutDialog')
    handleLayoutDialog() {
        this.$emit('layout-handle', this.layoutDialog);
    }

    pageRet() {
        this.getBankHgTransactionTableData();
    }

    getBankHgTransactionTableData() {
        if (JSON.stringify(this.transData.clickRow) == '{}') {
            return;
        }
        this.loading = true;
        this.$axios
            .post('/productSelect/bankHgTransaction', {
                paging: this.page,
                sort: this.sort,
                productCode: this.transData.clickRow.fundCode,
                productSerialNo: this.transData.clickRow.fundId,
            })
            .then((res: any) => {
                this.tableData = res.list;
                this.page.total = res.total;
                this.loading = false;
            })
            .catch(() => {
                this.loading = false;
            });
    }

    // 分页
    pageChange(curPage: number) {
        this.page.currentPage = curPage;
        this.getBankHgTransactionTableData();
    }

    // 排序改变
    private changeTableSort(column): void {
        this.sortProp = column.property;
        this.sortOrder = column.order;
        let sortType = column.order == 'asc' ? 'ASC' : column.order == 'desc' ? 'DESC' : '';
        this.sort = this.sortableObj[column.property] + ' ' + sortType;
        this.pageChange(1);
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        await this.queryLayout();
    }

    // 获取页面布局信息
    async queryLayout() {
        let resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/TN_HG_TRANSACTION')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });

        if (!resList) {
            // 新用户初始化
            const keys = this.resetNoSelectedFieldList.map(item => item.id);
            this.showFieldList = this.tableColumns.filter(item => !keys.includes(item.id));
        } else {
            if (resList.length < 1) {
                // 选项为空
                this.showFieldList = this.fixedFieldList;
            } else {
                this.showFieldList = this.fixedFieldList.concat(JSON.parse(resList));
                // const temps = this.fixedFieldList.concat(JSON.parse(resList)).map(item => item.id);
                // this.showFieldList = this.tableColumns.filter(item => temps.includes(item.id));
            }
        }
        const fixKeys = this.fixedFieldList.map(item => item.id);
        this.selectedFieldList = this.showFieldList.filter(item => !fixKeys.includes(item.id));
        this.tableKey++;
    }

    // beforeUpdate() {
    //     this.$nextTick(() => {
    //         // 在数据加载完，重新渲染表格
    //         (this.$refs['table'] as any).doLayout();
    //     });
    // }
    getAlign(ele) {
        let obj = this.tableColumns.find(item => item.id == ele.id);
        return (obj && obj.align) || 'right';
    }
}
</script>
<style lang="scss" scoped></style>
